package com.tcppag.fixedlength;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @author 罗俊华
 * @date 2021/8/26 - 6:13 下午
 */
@Slf4j
public class FixedLengthClient {

    public static void main(String[] args) {


        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new LoggingHandler())
                                .addLast(new StringEncoder(StandardCharsets.UTF_8));
                    }
                }).connect("localhost", 9908);

        channelFuture.addListener((ChannelFuture future) -> {
            Channel channel = future.channel();
            for (int i = 0; i < 20; i++) {
                channel.write(getFixedLengthContent(10));
            }
            channel.flush();

        });
    }

    static Random random = new Random();


    /**
     * 生成定长的字符串
     *
     * @return
     */
    public static String getFixedLengthContent(int length) {

        int index = random.nextInt(length);

        int c = random.nextInt(127);


        StringBuilder builder = new StringBuilder(length);

        for (int i = 0; i < index; i++) {
            builder.append((char) c);
        }

        for (int i = index; i < length; i++) {
            builder.append("_");
        }
        return builder.toString();

    }

}
